<template>
  <button class="submit" v-if="!token" :disabled="disabled" @click.stop="onLogin"></button>
</template>

<script setup>
import { computed, ref } from 'vue'
import to from 'await-to-js'
import { login, getInfo } from '@/api/user'
import { toast } from '@/utils/uni-app'
import { jump } from '@/utils/router'
import useUserStore from '@/store/user'
import { onShow } from '@dcloudio/uni-app'

const props = defineProps({
  // 是否静默登录
  silentLogin: Boolean
})

const userStore = useUserStore()
const token = computed(() => userStore.token)
const code = computed(() => userStore.code)

const getCode = async () => {
  console.log('code: ', code.value)
  if (token.value || (Date.now() <= code.value.at)) {
    return Promise.resolve(code.value)
  }

  const [codeErr, codeRes] = await uni.login()
  console.log('=== 获取 code ===')
  console.log(codeErr)
  console.log(codeRes)

  if (codeErr) {
    console.log(codeErr)
    return Promise.reject(codeErr)
  }

  userStore.setCode(codeRes.code)
  return Promise.resolve(code.value)
}

onShow(() => getCode())

const disabled = ref(false)
const resetDisabled = (msg) => {
  uni.hideLoading()
  msg && toast.info(msg)
  disabled.value = false
}

const onLogin = async () => {
  if (!props.silentLogin) {
    userStore.setLoginToast(true)
    return jump('/pages/main/user/index')
  }

  if (disabled.value) return false

  uni.showLoading({ mask: true })
  disabled.value = true

  const [wxInfoErr, wxInfoRes] = await uni.getUserProfile({ desc: '用户用户登录' })
  console.log(wxInfoErr, wxInfoRes)

  if (wxInfoErr) {
    if (wxInfoErr.errMsg === 'getUserProfile:fail auth deny') {
      wxInfoErr.errMsg = '用户取消授权'
    }

    return resetDisabled(wxInfoErr.errMsg)
  }

  const [codeErr, codeRes] = await to(getCode())
  console.log(codeErr, codeRes)

  if (codeErr) {
    return resetDisabled(codeErr.errMsg)
  }

  const params = {
    code: codeRes.value,
    anonymousCode: codeRes.value,
    encryptedData: wxInfoRes.encryptedData,
    iv: wxInfoRes.iv,
    avatar: wxInfoRes.userInfo.avatarUrl,
    nickName: wxInfoRes.userInfo.nickName,
    gender: wxInfoRes.userInfo.gender
  }

  const [loginErr, loginRes] = await to(login(params))
  console.log(loginErr, loginRes)

  userStore.setCode('')

  if (loginErr) {
    return resetDisabled()
  }

  if (!loginRes.token) {
    userStore.updateInfo({ openId: loginRes.openId })
    jump('/pages/user/signup/index')
    return resetDisabled()
  }

  const [infoErr, infoRes] = await to(getInfo(loginRes.token))
  console.log(infoErr, infoRes)

  if (infoErr) {
    return resetDisabled()
  }

  userStore.setToken(loginRes.token)

  const userInfo = Object.assign(
    { openId: loginRes.openId },
    infoRes
  )
  userStore.updateInfo(userInfo)
  resetDisabled('登录成功')
}
</script>

<style lang="scss" scoped>
button.submit {
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  opacity: 0;
  z-index: 9;
}
</style>
